import axios, { type AxiosInstance, type Method } from 'axios'
import { userConsultStore } from '@/stores'
// 1. 新axios实例，基础配置
// 1. 新的axios实例，基础配置
const baseURL1 = 'inspect/v1/public/'
const baseURL2 = 'ucenter/v1/party/'
const instance1 = axios.create({
  baseURL: baseURL1,
  timeout: 10000
})

const instance2 = axios.create({
  baseURL: baseURL2,
  timeout: 10000
})
// 对每个实例添加请求和响应的拦截器
const instances = [instance1, instance2]
// 2. 请求拦截器，携带token
instances.forEach((instance) => {
  // 请求拦截器，携带token
  instance.interceptors.request.use(
    (config) => {
      const store = userConsultStore()
      if (store.consult.token && config.headers) {
        config.headers['Authorization'] = `Bearer ${store.consult?.token}`
      }
      return config
    },
    (err) => Promise.reject(err)
  )
  // 响应拦截器，剥离无效数据，401拦截
  instance.interceptors.response.use(
    (res) => {
      return res.data
    },
    (err) => {
      return Promise.reject(err)
    }
  )
})

export { baseURL1, baseURL2, instance1, instance2 }
type Data<T> = {
  code: number
  message: string
  data: T
}

// 请求工具函数
export const request = <T>(
  instance: AxiosInstance,
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
